<script setup>
import {ref, defineExpose, defineEmits} from 'vue'
import {addArticleCate, editArticleCate, getArticleCate} from '@/api/article.js'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const cateFormRef = ref()
const cateForm = ref({
  cate_name: '',
  cate_alias: ''
})
const cateFormRules = ref({
  cate_name: [
    {required: true, message: '分类名称不能为空', trigger: 'blur'},
    {min: 1, max: 10, message: '1-10位大小写字母和数字', trigger: 'blur'}
  ],
  cate_alias: [
    {required: true, message: '分类别名不能为空', trigger: 'blur'},
    {min: 1, max: 10, message: '1-10位大小写字母和数字', trigger: 'blur'}
  ]
})
// 组件对外暴露一个方法open，基于open传来的参数，区分添加还是编辑
// open({})=>表单无需渲染 添加
// open({id,cate_name,...})=>表单需要渲染 编辑
const open = (row) => {
  dialogVisible.value = true
  cateForm.value = {...row}  // 添加-》重置了表单内容。编辑-》回显数据
}
defineExpose({
  open
})
//确认
const confirmBtn = async () => {
  await cateFormRef.value.validate()
  if (cateForm.value.id) {
    // 编辑
    await editArticleCate(cateForm.value)
    ElMessage.success('编辑成功')
  } else {
    // 添加
    await addArticleCate(cateForm.value)
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
  emit('success')
}
</script>

<template>

  <el-dialog
      v-model="dialogVisible"
      :title="cateForm.id?'编辑分类':'添加分类'"
  >
    <el-form ref="cateFormRef" :model="cateForm" :rules="cateFormRules">
      <el-form-item prop="cate_name" label="分类名称">
        <el-input v-model="cateForm.cate_name" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item prop="cate_alias" label="分类别名">
        <el-input v-model="cateForm.cate_alias" placeholder="请输入"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBtn">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

